package com.chexiehui.jc.ui.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.SizeUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.entity.CarInfo;
import com.chexiehui.jc.event.MyCarInfoChangeEvent;
import com.chexiehui.jc.mvp.mine.MyCarListCovenant;
import com.chexiehui.jc.mvp.mine.MyCarListPresenter;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.LoadingLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * @Description 我的爱车
 * @Auth SongJun
 * @Date 2020/05/21 00:18
 **/
public class MyCarListActivity extends BaseMvpActivity<MyCarListPresenter> implements MyCarListCovenant.View {

    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.recycler)
    SwipeRecyclerView mRecycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private List<CarInfo> listData;
    private CommonAdapter<CarInfo> listAdapter;
    private boolean isCurrentTag;

    @Override
    protected int getLayout() {
        return R.layout.activity_my_car_list;
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("我的爱车")
                .setRightTextDrawable(R.mipmap.ic_add_32)
                .setOnRightTextClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        startActivity(MyCarAddActivity.class);
                    }
                });
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void initView(Bundle bundle) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        refreshLayout.setEnableOverScrollDrag(true);
        refreshLayout.setDragRate(0.5f);

        mRecycler.setLayoutManager(new LinearLayoutManager(mContext));
        mRecycler.setSwipeMenuCreator((leftMenu, rightMenu, position) -> {
            SwipeMenuItem deleteItem = new SwipeMenuItem(mContext);
            deleteItem.setBackgroundColor(ContextCompat.getColor(mContext, R.color.c_FD4C34));
            deleteItem.setTextColor(ContextCompat.getColor(mContext, R.color.colorWhite));
            deleteItem.setText("删除");
            deleteItem.setWidth(SizeUtils.dp2px(100));
            deleteItem.setHeight(SizeUtils.dp2px(90));
            rightMenu.addMenuItem(deleteItem); // 在Item右侧添加一个菜单。
        });
        mRecycler.setOnItemMenuClickListener(new OnItemMenuClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge, int position) {
                if (NoDoubleClickUtils.isDoubleClick()) {
                    return;
                }
                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                menuBridge.closeMenu();
                // 是否右侧菜单：菜单在Item中的Position：
                if(SwipeRecyclerView.RIGHT_DIRECTION == menuBridge.getDirection() &&
                        menuBridge.getPosition() == 0){
                    mvpPresenter.deleteCar(listData.get(position).getId(), position);
                }
            }
        });
        listData = new ArrayList<>();
        listAdapter = new CommonAdapter<CarInfo>(mContext, R.layout.item_my_car, listData) {
            @Override
            protected void convert(ViewHolder holder, CarInfo item, int position) {
                GlideUtil.loadImageViewCrop(mContext, item.getImg(), holder.getView(R.id.iv_item_image),
                        R.drawable.shape_square, R.drawable.shape_square);
                holder.setText(R.id.tv_item_name, item.getSeriesName());
                holder.setText(R.id.tv_item_model, item.getSeriesName() + item.getOutput() + item.getSizeType());
                holder.setText(R.id.tv_item_state, item.getApplicationStateStr());
                TextView tv_item_state = holder.getView(R.id.tv_item_state);
                tv_item_state.setText(item.getApplicationStateStr());
                if(!item.getApplicationState().equals("1")){
                    Drawable drawable= getResources().getDrawable(R.mipmap.ic_car_auth_state_no);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    tv_item_state.setCompoundDrawables(drawable,null,null,null);
                }else{
                    tv_item_state.setCompoundDrawables(null,null,null,null);
                }
            }
        };
        mRecycler.setAdapter(listAdapter);
        listAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                startActivity(MyCarEditActivity.class, new BundleBuilder().putSerializable("entity", listData.get(position)).create());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        loadingLayout.setOnReloadListener(v -> {
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList();
        });
        refreshLayout.setOnRefreshListener(refreshLayout -> mvpPresenter.getList());
        mvpPresenter.getList();
    }

    @Override
    protected MyCarListPresenter createPresenter() {
        return new MyCarListPresenter(this);
    }

    @Override
    public void onGetListSuccess(BaseModel<List<CarInfo>> successResult) {
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
        }
        listData.clear();
        listData.addAll(successResult.getData());
        listAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (listData.size() > 0) {
                    listData.clear();
                    listAdapter.notifyDataSetChanged();
                }
            }
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText(failureResult.getResultInfo());
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (listData.size() <= 0) {
                loadingLayout.setStatus(LoadingLayout.Error);
                loadingLayout.setErrorText(failureResult.getResultInfo());
            } else {
                showToast(failureResult.getResultInfo());
            }
        }
    }

    @Override
    public void onDeleteCarSuccess(BaseModel<Map<String, Object>> successResult) {
        showToast(successResult.getResultInfo());
        String id = (String) successResult.getData().get("id");
        Integer position = (Integer) successResult.getData().get("position");
        isCurrentTag = true;
        EventBus.getDefault().post(new MyCarInfoChangeEvent());
        if(id != null && position != null){
            if(listData.size() > position){
                if(listData.get(position).getId().equals(id)){
                    int p = position;
                    listData.remove(p);
                    listAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    public void onDeleteCarFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Subscribe
    public void onMyCarInfoChangeEvent(MyCarInfoChangeEvent event){
        if(isCurrentTag){
            isCurrentTag = false;
            return;
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getList();
    }

}